import {
  Body,
  Controller,
  Get,
  HttpException,
  HttpStatus,
  Param,
  Post,
  UseGuards,
} from '@nestjs/common';
import {
  ApiBasicAuth,
  ApiBearerAuth,
  ApiHeader,
  ApiOperation,
  ApiParam,
  ApiResponse,
  ApiTags,
} from '@nestjs/swagger';
import { InjectRepository } from '@nestjs/typeorm';
import { CurrentUser } from 'src/decorators/current.user';
import { ApiTagDeleteDto } from 'src/types/modules/tag/dto/delete-tag.dto';
import {
  ApiTagGetDto,
  ApiTagGetResult,
} from 'src/types/modules/tag/dto/get-tag.dto';
import { ApiTagPutDto } from 'src/types/modules/tag/dto/put-tag.dto';
import { Tag } from 'src/types/modules/tag/entities/tag.type';
import { UserEntity } from 'src/types/modules/user/entities/user.entity';
import { syncValidate, unallow } from 'src/utils/validate';
import { getRepository, Repository } from 'typeorm';

import { TagService } from './tag.service';
import { JwtAuthGuard } from 'src/modules/user/jwt/jwt-auth.guard';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { CurrentRole } from '@/decorators/current.role';
import { ClientRole } from '@/modules/user/role/role.type';

@ApiTags('分组')
@ApiBearerAuth()
@Controller()
export class TagController {
  constructor(
    @InjectModel('tag') private tagModel: Model<Tag>,
    private tagService: TagService,
  ) {}

  @ApiOperation({ summary: '创建与修改分组' })
  @UseGuards(JwtAuthGuard)
  @Post('tag/put')
  async put(
    @Body() { _id, ...params }: ApiTagPutDto,
    @CurrentUser() user: UserEntity,
    @CurrentRole() role: ClientRole,
  ) {
    try {
      await syncValidate(params, {
        type: {
          required: true,
          type: 'string',
        },
        name: {
          required: true,
        },
      });
    } catch (e) {
      throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
    }
    const data = unallow(params, []);
    if (_id) {
      data.updateAt = Date.now();
      // 保存
      const updateRes = await this.tagModel.updateOne({ _id }, data);
      return data;
    } else {
      data.teamId = role.teamId;
      data.userId = user.id;
      data.createAt = Date.now();
      data.updateAt = Date.now();
      const created = new this.tagModel(data);
      created.validateSync({ validateBeforeSave: false });
      const res = await created.save();
      return res;
    }
  }

  @ApiOperation({ summary: '获取分组' })
  @ApiResponse({
    type: ApiTagGetResult,
  })
  @UseGuards(JwtAuthGuard)
  @Post('/tag/get')
  async get(
    @Body() params: ApiTagGetDto,
    @CurrentUser() u: UserEntity,
    @CurrentRole() role: ClientRole,
  ) {
    try {
      await syncValidate(params, {
        type: {
          required: true,
        },
      });
    } catch (e) {
      throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
    }
    const { type, keywords, parentId } = params;
    return this.tagService.getAll(type, role.teamId, keywords, parentId);
  }

  // @ApiOperation({ summary: '获取子分组' })
  // @ApiResponse({
  //   type: ApiTagGetResult,
  // })
  // @Post('/tag/getChilds')
  // async getChilds(@Body() params: ApiTagGetDto) {
  //   try {
  //     await syncValidate(params, {
  //       tag_type: {
  //         required: true,
  //         type: 'enum',
  //         enum: [1, 2],
  //       },
  //     });
  //   } catch (e) {
  //     throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
  //   }
  //   const { tag_type } = params;
  //   return this.tagService.getTagsAllChild(tag_type, [3, 30], 3);
  // }

  @ApiOperation({ summary: '删除分组' })
  @UseGuards(JwtAuthGuard)
  @Post('/tag/delete')
  async delete(
    @Body() params: ApiTagDeleteDto,
    @CurrentUser() u: UserEntity,
    @CurrentRole() role,
  ) {
    // @TODO: 应该校验团队权限是否为可靠
    try {
      await syncValidate(params, {
        _id: {
          required: true,
        },
      });
    } catch (e) {
      throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
    }
    return this.tagService.deleteById(params._id, role.teamId);
  }
}
